package com.chase.passwordmaster.encoder

import com.chase.passwordmaster.encoder.encoder_v2.EncoderV2

interface Encoder {
    /**
     * 获取加密后的字符串
     * Get encrypted string
     *
     * @param content
     * @return String a new encrypted string
     */
    fun encode(content: String): String

    /**
     * 获取解密后的字符串
     * Get decrypted string
     *
     * @param content
     * @return String a new decrypted string
     */
    fun decode(content: String): String

    /**
     * 内容由当前encoder加密？
     * Is the content encrypted by current encoder?
     *
     * @param content
     * @return Boolean whether matched
     */
    fun match(content: String): Boolean
    fun refresh(encoderRefreshInfo: EncoderRefreshInfo)
}

open class EncoderRefreshInfo(
    val oldLoginPass: String,
    val newLoginPass: String
)

enum class EncodeExceptionCode {
    NO_MATCHED_ENCODER,
    V2_NO_GLOBAL_DATA_RSA_KEY_PAIR,
    V2_NO_GLOBAL_DATA_LOGIN_PASSWORD
}

open class EncoderException(var encodeExceptionCode: EncodeExceptionCode): Exception()

val encoders = listOf<Encoder>(EncoderV2)

/**
 * 获取加密后的字符串
 * Get encrypted string
 *
 * @return String a new encrypted string
 */
fun String.encoded() = encoders[0].encode(this)

/**
 * 获取解密后的字符串
 * Get decrypted string
 *
 * @return String a new decrypted string
 */
fun String.decoded(): String {
    encoders.forEach {
        if (it.match(this)) {
            return it.decode(this)
        }
    }
    throw EncoderException(EncodeExceptionCode.NO_MATCHED_ENCODER)
}

fun refreshEncoder(encoderRefreshInfo: EncoderRefreshInfo) = encoders[0].refresh(encoderRefreshInfo = encoderRefreshInfo)